package com.koron.housing.info.excel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.housing.info.bean.dto.HousingInfoExcel;
import com.koron.housing.info.bean.po.HousingInfo;
import com.koron.housing.info.service.HousingInfoService;
import org.koron.ebs.mybatis.ADOConnection;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jzp
 * @since 2022/6/14
 */
public class HousingInfoImportListener extends AnalysisEventListener<HousingInfoExcel> {
    private static final int BATCH_COUNT = 100;
    private final HousingInfoService housingInfoService;
    private List<HousingInfoExcel> housingInfoExcelList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public HousingInfoImportListener(HousingInfoService housingInfoService) {
        this.housingInfoService = housingInfoService;
    }

    @Override
    public void invoke(HousingInfoExcel data, AnalysisContext context) {
        // 默认闲置
        data.setStatus("0");
        // 设置标题，地址+房号
        data.setTitle(data.getAddress()+data.getRoomNum());
        housingInfoExcelList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (housingInfoExcelList.size() >= BATCH_COUNT) {
            saveHousingInfo();
            // 存储完成清理 list
            housingInfoExcelList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveHousingInfo();
    }

    private void saveHousingInfo() {
        if (CollUtil.isEmpty(housingInfoExcelList)) {
            return;
        }
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), factory -> {
            List<HousingInfo> collect = housingInfoExcelList.stream().map(e -> BeanUtil.toBean(e, HousingInfo.class)).collect(Collectors.toList());
            return housingInfoService.saveBatch(factory, collect);
        }, Boolean.class);
    }

}
